var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var lessMiddleware = require('less-middleware');
var logger = require('morgan');
var cors = require('cors');
const session = require("express-session");
//body-parser 解析表单
const bodyParser = require('body-parser');

var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var apiRouter = require('./routes/api');
var qiniuRouter = require('./routes/qiniu');
var aliossRouter = require('./routes/alioss');

var app = express();

// CORS模块，处理web端跨域问题
app.use(cors());

/*app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');//允许的域名
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');//服务器支持的头信息
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');//允许的方法
  //res.header("X-Powered-By",' 3.2.1');
  //res.header("Content-Type", "application/json;charset=utf-8");
  next();
});*/

//使用mysql中间件连接MySQL数据库
// const mysql = require('mysql');
// const connection = mysql.createConnection({
//   host: '127.0.0.1',           //数据库地址
//   user: 'root',                //用户名
//   password: '',                //密码
//   port: '3306',                //端口
//   database: 'hzsf',            //库名
//   multipleStatements: true     //允许执行多条语句
// });

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({extended: false}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: false}));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  secret: "d1025ok",		//设置签名秘钥  内容可以任意填写
  cookie: {maxAge: 24 * 60 * 60 * 1000},		//设置cookie的过期时间，例：1天后session和相应的cookie失效过期
  resave: true,			//强制保存，如果session没有被修改也要重新保存
  saveUninitialized: false		//如果原先没有session那么久设置，否则不设置
}));

app.use('/', indexRouter);
app.use('/api/admin', adminRouter);
app.use('/api', apiRouter);
app.use('/api/qiniu', qiniuRouter);
app.use('/api/alioss', aliossRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
